/**
 * Created by chenxq on 2018/1/2.
 */
import React,{PureComponent,Component} from 'react';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import {Card,Table,Row,Col,Select,DatePicker,Divider,Avatar,Input,Button,Form,message} from 'antd';
import request from '../../utils/request';
import {connect} from 'dva';
import {listParams,followType} from '../defaultData';
import {convertLongToString ,findObjByKey} from '../../utils/index'
import { Link } from 'dva/router';

const FormItem = Form.Item;
const { Option } = Select;
const {RangePicker}= DatePicker;
@connect(state=>({
  currentUser: state.user.currentUser,
  })
)
export default class extends PureComponent{

  state={
    detail:{},
    list:[],
    pagination:{...listParams},
    loading:false,
    total:0
  }
  getDetail=()=>{
    let _this=this;
    request(`/v1/customer/plan/service/overview`,{method:'POST'}).then(jsonData=>{
      if(jsonData.result){
        console.log('jsss',jsonData);
        _this.setState({
          detail:jsonData.data || {}
        })
      }
    })
  }
  search=(params)=>{
    let pagination={
      ...listParams,
      ...params
    }
    this.getList(pagination);
  }
  getList=(page={current:1})=>{
    let _this=this;
    let pagination=this.state.pagination;
    let params={...pagination,
      ...page
    }
    params.page=params.current;
    this.setState({
      pagination:params,
      loading:true
    })
    console.log('search',params);
    request('/v1/customer/plan/todo',{
      method:'POST',
      body:{
        ...params
      }
    }).then(jsonData=>{
      let data=jsonData.data || {};
      let total=data.total || 0;
      let list=data.list || [];
      _this.setState({
        loading:false,
        total,
        list
      })
      if(!jsonData.result){
        message.error(jsonData.msg || '获取数据失败');
      }
    })

  }
  componentDidMount(){
    this.getDetail();
    this.getList();

  }
  getDescription=()=>{
    let {detail} = this.state;
    return (<div>
      {detail.group ||'分组名'}
      <Divider type="vertical" />
      {detail.agentNo || '分机号'}
    </div>)
  }
  columns=[{
    title:'客户名称',
    dataIndex:'customerName'
  },{
    title:'回访时间',
    dataIndex:'planAlert',
    render(time){
      return time? convertLongToString(time) :'';
    }
  },{
    title:'创建时间',
    dataIndex:'createTime',
    render(time){
      return time? convertLongToString(time) :'';
    }
  },{
    title:'回访方式',
    dataIndex:'planType',
    render(type){
      return type?findObjByKey(followType,type).name :'';
    }
  },{
    title:'回访内容',
    dataIndex:'planContent'
  },{
    title:'查看',
    dataIndex:'customerId',
    render: (customerId) => {
      return (<div><Link to={`/customer/detail/${customerId}`}>客户详情</Link></div> );
    },

  },
    {
      title:'操作',
      dataIndex:'planId',
      render: (planId) => {
        return (<div> <a onClick={this.planExecute.bind(this, planId)}>关闭计划</a></div> );
      },

    }]
  planExecute=(planId)=>{
    this.props.dispatch({
      type: 'plan/fetchRemove',
      payload: {
        planId,
      }
    }).then(jsonData => {
      if (jsonData.result) {
        message.success('保存成功', 0.8, () => {
          this.getList();
        })
      } else {
        message.error(jsonData.msg || '操作失败')
      }
    })
  }
  render(){
    let {currentUser} = this.props;
    let {detail} = this.state;
    return (<div>
      <Card title="工作台">
        <Card.Meta style={{float:'left'}}
          avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
          title={`您好，${currentUser.userName}，祝您开心每一天`}
          description={this.getDescription()}
        />
        <div className="flex-row" style={{float:"right"}}>
          <div style={{textAlign:"center"}}>
            <p>今日客户数</p>
            <p style={{fontSize:24}}>{detail.todayCustomerNum}</p>
          </div>
          <Divider type="vertical" style={{height:40,margin:20}}></Divider>
          <div style={{textAlign:"center"}}>
            <p>拜访人数</p>
            <p style={{fontSize:24}}>{detail.planNum}</p>
          </div>
          <Divider type="vertical" style={{height:40,margin:20}}></Divider>
          <div style={{textAlign:"center"}}>
            <p>客户总数</p>
            <p style={{fontSize:24}}>{detail.totalCustomerNum}</p>
          </div>
        </div>
      </Card>
      <Card title="今日拜访客户" style={{marginTop:20}}>
        <div>
          <SearchInput search={this.search}></SearchInput>
        </div>
        <Table columns={this.columns}
               rowKey="planId"
               loading={this.state.loading}
               pagination={{...this.state.pagination,total:this.state.total}}
               dataSource={this.state.list}
               onChange={this.getList}
               style={{marginTop:20}}

        ></Table>
      </Card>
    </div>)
  }

 }



const searchArr=[{key:'customerName',title:'客户姓名'},{key:'phone',title:'手机号码'}];


export class SearchInput extends Component{
  constructor(props){
    super(props);
    let arr=this.props.searchArr || searchArr;
    this.state={
      searchArr:arr,
      key:this.props.key ||  arr[0].key,
      keyword:'',
      startTime:null,
      endTime:null
    }
  }
  hanldeSearch=()=>{
    let {key,keyword,startTime,endTime} = this.state;
    this.props.search && this.props.search.call(null,{
      searchKey:key,
      searchVal:keyword,
      startTime,
      endTime
    })
  }
  changeTime=(times)=>{
    let {key,keyword} = this.state;
    let startTime=null,
        endTime=null
    if(times.length==2){
      startTime=times[0].format('X');
      endTime=times[1].format('X');
    }
    this.props.search && this.props.search.call(null,{
      searchKey:key,
      searchVal:keyword,
      startTime,
      endTime
    });
    this.setState({
      startTime,
      endTime
    })
  }
  render(){
    let {searchArr,key} = this.state;
    return (<Row gutter={24}>
      <Col span={8}>
        <Input  addonBefore={
          <Select value={key} style={{ width: 100 }} onChange={(value)=>{
            this.setState({
              key:value
            })
          }
          }>{
            searchArr.map(item=>(<Option key={item.key} value={item.key}>{item.title}</Option>))
          }
          </Select>
        }  placeholder={this.props.placeholder || "关键字查询"}
                onChange={(e)=>{
                  this.setState({
                    keyword:e.target.value
                  })
                }}
                onPressEnter={this.hanldeSearch} />
      </Col>
      <Col span={8}>
        <RangePicker onChange={this.changeTime} />
      </Col>
      <Col span={4}>
        <Button style={{marginLeft:15}} type="primary" onClick={this.hanldeSearch}>{this.props.searchBtnText || '查询'}</Button>
      </Col>
    </Row>)
  }
}
